package com.huifaapp.mall.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.WaitPayAdapter;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.base.bean.PayBean;
import com.huifaapp.mall.bean.WaitpayBean;
import com.huifaapp.mall.bean.event.OrderStatusEventMessage;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.AlipayUtils;
import com.huifaapp.mall.view.TakePhotoPopWin;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.squareup.okhttp.Request;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class WaitPayActivity extends AppCompatActivity implements TakePhotoPopWin.OnItemClickListener{


    private RecyclerView Reshopview;
    private TextView recename,recephone,receaddress,runprice,redbag,sjprice,sxtime;
    private TextView creatpay,ddnum;
    private WaitpayBean.DataBean goods;
    private List<WaitpayBean.DataBean.OrderItemBean> orderdata;
    private Button bt_cancel;
    private Button bt_fkmoney;
    TakePhotoPopWin mPop;
    WindowManager.LayoutParams params;
    private Button bt_kefu;
    String orderNo;
    private TextView tv_huijinbi,tv_zfjy;

    private WaitpayBean.DataBean.OrderItemBean orderItemBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wait_pay);
        initView();
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = getIntent();
        orderNo = intent.getStringExtra("orderNo");
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"orders/notpayeddetail")
                // "token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3&orderNo="+orderNo)
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(WaitPayActivity.this))
                .addParams("orderNo",orderNo)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
            }

            @Override
            public void onResponse(String response) {

                try {

                    Gson gson = new Gson();
                    WaitpayBean waitPayBean = gson.fromJson(response,WaitpayBean.class);
                    goods = waitPayBean.getData();
                    orderdata = goods.getOrderItem();
                    WaitPayAdapter waitPayAdapter = new WaitPayAdapter(WaitPayActivity.this,goods,orderdata);
                    Reshopview.setLayoutManager(new LinearLayoutManager(WaitPayActivity.this));
                    Reshopview.setAdapter(waitPayAdapter);
                    recename.setText(waitPayBean.getData().getReceiverName());
                    recephone.setText(waitPayBean.getData().getReceiverPhone());
                    receaddress.setText(waitPayBean.getData().getReceiverAddress());
                    runprice.setText("¥"+waitPayBean.getData().getExpressfee()+"");
                    redbag.setText("¥"+waitPayBean.getData().getCouponAmount()+"");
                    sjprice.setText("¥"+waitPayBean.getData().getActualpay()+"");
                    tv_huijinbi.setText("¥"+waitPayBean.getData().getPointsAmount()+"");
                    creatpay.setText(waitPayBean.getData().getCreatetime());
                    ddnum.setText(waitPayBean.getData().getOrderNo()+"");
                    tv_zfjy.setText(waitPayBean.getData().getPayno()+"");



                }catch (Exception e){
                    ToastUtils.showShort("获取失败");

                }
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Intent intent = getIntent();
        orderNo = intent.getStringExtra("orderNo");
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"orders/notpayeddetail")
                // "token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3&orderNo="+orderNo)
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(WaitPayActivity.this))
                .addParams("orderNo",orderNo)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
            }

            @Override
            public void onResponse(String response) {

                try {

                    Gson gson = new Gson();
                    WaitpayBean waitPayBean = gson.fromJson(response,WaitpayBean.class);
                    goods = waitPayBean.getData();
                    orderdata = goods.getOrderItem();
                    WaitPayAdapter waitPayAdapter = new WaitPayAdapter(WaitPayActivity.this,goods,orderdata);
                    Reshopview.setLayoutManager(new LinearLayoutManager(WaitPayActivity.this));
                    Reshopview.setAdapter(waitPayAdapter);
                    recename.setText(waitPayBean.getData().getReceiverName());
                    recephone.setText(waitPayBean.getData().getReceiverPhone());
                    receaddress.setText(waitPayBean.getData().getReceiverAddress());
                    runprice.setText("¥"+waitPayBean.getData().getExpressfee()+"");
                    redbag.setText("¥"+waitPayBean.getData().getCouponAmount()+"");
                    sjprice.setText("¥"+waitPayBean.getData().getActualpay()+"");
                    tv_huijinbi.setText("¥"+waitPayBean.getData().getPointsAmount()+"");
                    creatpay.setText(waitPayBean.getData().getCreatetime());
                    ddnum.setText(waitPayBean.getData().getOrderNo()+"");
                    tv_zfjy.setText(waitPayBean.getData().getPayno()+"");

                }catch (Exception e){
                    ToastUtils.showShort("获取失败");

                }
            }
        });
    }

    private void initView() {
        bt_kefu = (Button) findViewById(R.id.wait_pay_kefu);
        Reshopview = (RecyclerView) findViewById(R.id.Reshopview);
        recename = (TextView) findViewById(R.id.waitpay_recename);
        recephone = (TextView) findViewById(R.id.waitpay_recephone);
        receaddress = (TextView) findViewById(R.id.waitpay_address);
        runprice = (TextView) findViewById(R.id.waitpay_runpay);
        redbag = (TextView) findViewById(R.id.waitpay_redbag);
        sjprice = (TextView) findViewById(R.id.waitpay_sjprice);
        ddnum = (TextView) findViewById(R.id.waitpay_ddnum);
        creatpay = (TextView) findViewById(R.id.waitpay_creattime);
        bt_cancel = (Button) findViewById(R.id.waitpay_cancel);
        bt_fkmoney = (Button) findViewById(R.id.waitpay_btfkmoney);
        tv_huijinbi = (TextView) findViewById(R.id.waitpay_hjbzk);
        tv_zfjy = (TextView) findViewById(R.id.waitpay_zfjy);

        //  sxtime = (TextView) findViewById(R.id.shixiaotime);
        Intent intent = getIntent();
        orderNo = intent.getStringExtra("orderNo");
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"orders/notpayeddetail")
                // "token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3&orderNo="+orderNo)
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(WaitPayActivity.this))
                .addParams("orderNo",orderNo)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
            }

            @Override
            public void onResponse(String response) {

                try {

                    Gson gson = new Gson();
                    WaitpayBean waitPayBean = gson.fromJson(response,WaitpayBean.class);
                    goods = waitPayBean.getData();
                    orderdata = goods.getOrderItem();
                    WaitPayAdapter waitPayAdapter = new WaitPayAdapter(WaitPayActivity.this,goods,orderdata);
                    Reshopview.setLayoutManager(new LinearLayoutManager(WaitPayActivity.this));
                    Reshopview.setAdapter(waitPayAdapter);
                    recename.setText(waitPayBean.getData().getReceiverName());
                    recephone.setText(waitPayBean.getData().getReceiverPhone());
                    receaddress.setText(waitPayBean.getData().getReceiverAddress());
                    runprice.setText("¥"+waitPayBean.getData().getExpressfee()+"");
                    redbag.setText("¥"+waitPayBean.getData().getCouponAmount()+"");
                    sjprice.setText("¥"+waitPayBean.getData().getActualpay()+"");
                    tv_huijinbi.setText("¥"+waitPayBean.getData().getPointsAmount()+"");
                    creatpay.setText(waitPayBean.getData().getCreatetime());
                    ddnum.setText(waitPayBean.getData().getOrderNo()+"");
                    tv_zfjy.setText(waitPayBean.getData().getPayno()+"");



                }catch (Exception e){
                    ToastUtils.showShort("获取失败");

                }
            }
        });
    }

    private void initData() {

        //取消订单
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AlertDialog alertDialog = new AlertDialog.Builder(WaitPayActivity.this).setTitle("提示").setMessage("是否需要取消？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                final String order = goods.getOrderNo();
                                OkHttpUtils.post().url("http://develop.jhjvip.cn:8080/mall/mobile/orders/cancelorders")
                                        .addParams("token",SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                                        .addParams("appId",AUniqueIdentifier.getDeviceId(WaitPayActivity.this))
                                        .addParams("orderNo",order)
                                        .build()
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onError(Request request, Exception e) {
                                                ToastUtils.showShort("取消失败");
                                            }

                                            @Override
                                            public void onResponse(String response) {
                                                Log.e("HB",response);
                                                try {
                                                    JSONObject jsonObject = new JSONObject(response);
                                                    String code =  jsonObject.getString("code");
                                                    if (code.equals("10000"))
                                                    {
                                                        ToastUtils.showShort("删除成功");
                                                        orderdata.remove(goods.getOrderNo());
                                                        EventBus.getDefault().post(new OrderStatusEventMessage(
                                                                OrderStatusEventMessage.TYPE_RECEIVED,
                                                                orderNo));
                                                    }else {
                                                        ToastUtils.showShort("删除失败");
                                                    }

                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }


                                            }
                                        });

                            }
                        }).create();
                alertDialog.show();

            }

        });

        mPop=new TakePhotoPopWin(WaitPayActivity.this);
        mPop.setOnItemClickListener(WaitPayActivity.this);
        mPop.setFocusable(false);
        bt_kefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WaitPayActivity.this, com.huifaapp.mall.activity.Homefragment.WebActivity.class);
                intent.putExtra("url",ApiManager.KEFU);
                startActivity(intent);
            }
        });
        //付款
        bt_fkmoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //设置PopupWindow中的位置
                mPop.showAtLocation(WaitPayActivity.this.findViewById(R.id.main_view_waitpay), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);


            }
        });

    }
    @Override
    public void setOnItemClick(View v) {
        switch (v.getId()){
            case R.id.tv_true_pay:
//                params = getWindow().getAttributes();
//                params.alpha=1f;
//                getWindow().setAttributes(params);
                mPop.dismiss();
                pay(goods.getOrderNo());
                break;
            case R.id.ll_ye_pay:
//
                break;
            case R.id.ll_wx_pay:
                method="1";
                break;
            case R.id.ll_zfb_pay:
                method="2";
                break;
            case R.id.ll_fq_pay:

                break;
            case R.id.ll_ye_pay_no:

                break;
            case R.id.iv_pay_close:

                    mPop.dismiss();
                break;

        }
    }
    String method = "1"; //支付方式 1 微信支付，2支付宝支付。
    private void pay(String orderNo){

        if ("1".equals(method)) {
            String url = ApiManager.WXPAY_PAY+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+AUniqueIdentifier.getDeviceId(WaitPayActivity.this)+"&orderNo="+orderNo;
//            String url = ApiManager.WXPAY_PAY+"?token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3"
//                    +"&orderNo="+orderNo;
            Log.e("WEB", "路径Pay=====" + url);
            HttpUtils http = new HttpUtils();
            http.send(HttpRequest.HttpMethod.POST, url, new RequestCallBack<String>() {
                @Override
                public void onLoading(long total, long current, boolean isUploading) {
//                  testTextView.setText(current + "/" + total);
                    Log.e("数据", "数据-------" + current + "/" + total);
                }

                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
//                    textView.setText(responseInfo.result);

                    try {
                        Log.e("数据123", "数据payd-------" + responseInfo.result);
                        Gson gson = new Gson();
                        PayBean list = gson.fromJson(responseInfo.result, PayBean.class);

                        if(list.getCode().equals("10000")) {
                            Log.e("数据123", "数据list-------" + list);
                            IWXAPI mWxApi = WXAPIFactory.createWXAPI(WaitPayActivity.this, list.getData().getAppid(), true);
                            mWxApi.registerApp(list.getData().getAppid());
                            PayReq req = new PayReq();
                            req.appId = list.getData().getAppid();
                            req.partnerId = list.getData().getMch_id();
                            req.prepayId = list.getData().getPrepay_id();
                            req.nonceStr = list.getData().getNonce_str();
                            req.timeStamp = list.getData().getTimestamp();
                            req.packageValue ="Sign=WXPay";
                            req.sign = list.getData().getSign();
                            //在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            Log.e("数据123", "数据payd-------" + req);
                            mWxApi.sendReq(req);
                            Log.e("数据123", "mWxApi-------" + mWxApi);
                        }else{
                            Toast.makeText(WaitPayActivity.this,list.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }catch (JsonSyntaxException e){
                        Toast.makeText(WaitPayActivity.this,"未知错误",Toast.LENGTH_LONG).show();
                    }

                }
                @Override
                public void onStart() {
                }

                @Override
                public void onFailure(HttpException error, String msg) {
                }
            });
        } else if ("2".equals(method)) {
            new AlipayUtils(WaitPayActivity.this).getAlipaySignature(orderNo,SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN),AUniqueIdentifier.getDeviceId(WaitPayActivity.this));
        } else {
            ToastUtils.showShortSafe("获取信息失败!");
        }
    }


}
